const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.Types.ObjectId

const DialogSchema = new Schema({
  // 会话类型：0为一对一，1为群组
  type: {
    type: Number,
    default: 0
  },
  // 会话名称
  name: {
    type: String,
    default: ''
  },
  // 图标
  icon: {
    type: String,
    default: 'https://chenjiyuan.oss-cn-beijing.aliyuncs.com/user/_/group.png'
  },
  meta: {
    createdAt: {
      type: Date,
      default: Date.now()
    },
    updatedAt: {
      type: Date,
      default: Date.now()
    }
  },
  // 会话创建人
  createdBy: {
    type: ObjectId,
    ref: 'User'
  },
  // 用户会话列表是否显示
  showTo: [{
    type: ObjectId,
    ref: 'User'
  }],
  // 会话成员
  members: [{
    type: ObjectId,
    ref: 'User'
  }]
})

DialogSchema.pre('save', function(next) {
  if (this.isNew) {
    this.meta.createdAt = this.meta.updatedAt = Date.now()
  } else {
    this.meta.updatedAt = Date.now()
  }

  next()
})

DialogSchema.pre('save', function(next) {
  if (!this.isModified('members')) return next()
  if (this.members.length > 200) {
    next(new Error('群组成员最多200人'))
  } else {
    next()
  }
})

DialogSchema.set('toJSON', { virtuals: true })

mongoose.model('Dialog', DialogSchema)